/**
 * 
 */
package com.huawei.classroom.student.h56;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

/**
 * @author Administrator
 *
 */
public class FileTool {
	 
	/**
	 * 将homeDir 目录下（包括子目录）所有的文本文件（扩展名为.txt，扩展名不是.txt的文件不要动，扩展名区分大小写) 文件中，orgStr替换为 targetStr
	 * 所有文本文件均为UTF-8编码
	 * 例如将某个目录中所有文本文件中的 南开大学 替换为 天津大学
	 * @param homeDir
	 * @param orgStr
	 * @param targetStr
	 * @throws IOException 
	 */
	public void replaceTxtFileContent(String homeDir,String orgStr,String targetStr){
		 InputStreamReader reader = null;
		 OutputStreamWriter writer = null;
		try {
			File home = new File(homeDir);
			 File[] listfiles = home.listFiles();
			 for(int i=0; i<listfiles.length; i++) {
				 if(listfiles[i].isDirectory()) {
					 replaceTxtFileContent(listfiles[i].getPath(), orgStr, targetStr);
				 }else if(listfiles[i].getName().endsWith(".txt")) {
					 
							StringBuffer buf = new StringBuffer();
							char[] chars = new char[1024];
							// InputStream in=new FileInputStream(filename);

							reader = new InputStreamReader(new FileInputStream(listfiles[i].getPath()), "UTF-8");
							int readed = reader.read(chars);
							while (readed != -1) {
								buf.append(chars, 0, readed);
								readed = reader.read(chars);
							}
							String txt = buf.toString();
							txt = txt.replaceAll(orgStr, targetStr);
							writer = new OutputStreamWriter(new FileOutputStream(listfiles[i].getPath()), "UTF-8");
							writer.write(txt);

				 }
			 }	
		}catch(IOException e) {
			
		}finally {
			close(reader);
			close(writer);
		}
		 
	}
	
	
	private void close(Closeable inout) {
		if (inout != null) {
			try {
				inout.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
